package pt.fct.mpc.lastfm.artist;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import pt.fct.mpc.lastfm.R;
import pt.fct.mpc.lastfm.connectivity.LastfmBluetoothUnavailableException;
import pt.fct.mpc.lastfm.connectivity.LastfmURL;
import pt.fct.mpc.lastfm.generic.ImageActivity;
import pt.fct.mpc.lastfm.generic.TextActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class ArtistInfoActivity extends Activity {

	private static final String TAG = "Last.fm Artist Info Activity";
	private boolean gotArtist = false;
	ArtistData artistDataSet = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.artist_info);

		// Reads the info sent by the intent
		Intent the_intent_that_gave_life_to_everything = getIntent();
		Bundle intent_data = the_intent_that_gave_life_to_everything
				.getExtras();

		if (intent_data == null) {
			Log.e(TAG, "No extra data");
			finish();
		}

		artistDataSet = (ArtistData) intent_data.getSerializable("artistserial");

		if (artistDataSet == null) {
			Log.e(TAG, "Null values from bundle: albumDataSet = "
					+ artistDataSet);
			finish();
		}

		if (!gotArtist)
			getArtistInfo();
		createArtistInfoTab();
	}

	private void getArtistInfo() {

		String artist_name = artistDataSet.getName();
		try {
			artist_name = URLEncoder.encode(artistDataSet.getName(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException("encoding problems");
		}

		String search_query = "?method=artist.getinfo" + "&artist="
				+ artist_name + "&api_key="
				+ getString(R.string.lastfm_api_key);

		String request_str = getString(R.string.lastfm_api_url) + search_query;

		LastfmURL request_url = null;
		try {
			request_url = new LastfmURL(request_str);
		} catch (MalformedURLException e3) {
			Log.d("ArtistActivity.getArtistInfo", "MalformedURLException");
		}

		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = null;
		try {
			sp = spf.newSAXParser();
		} catch (ParserConfigurationException e2) {
			Log.d("ArtistActivity.getArtistInfo",
					"ParserConfigurationException 151");
		} catch (SAXException e2) {
			Log.d("ArtistActivity.getArtistInfo", "SAXException");
		}

		XMLReader xr = null;
		try {
			xr = sp.getXMLReader();
		} catch (SAXException e1) {
			Log.d("ArtistActivity.getArtistInfo", "SAXException");
		}

		ArtistXmlHandler myExampleHandler = new ArtistXmlHandler();
		xr.setContentHandler(myExampleHandler);

		try {
			xr.parse(new InputSource(request_url.openStream()));
		} catch (IOException e) {
			Log.d("ArtistActivity.getArtistInfo", "IOException");
			e.printStackTrace();
		} catch (SAXException e) {
			Log.d("ArtistActivity.getArtistInfo", "SAXException");
			e.printStackTrace();
		} catch (LastfmBluetoothUnavailableException e) {
			e.printStackTrace();
		}

		request_url.finished();

		artistDataSet.setArtistInfo(myExampleHandler.getParsedData());
		this.gotArtist = true;
	}

	private void createArtistInfoTab() {
		ImageView imageView = (ImageView) findViewById(R.id.artist_img);
		
		String artist_image_str = getArtistImage();
		if ((artist_image_str != null) && (artist_image_str.length() > 0))
		{
			Log.d(TAG, "artist_image_str = "+artist_image_str);
			imageView.setImageBitmap(urlToImage(artist_image_str));
		}

		TextView artistNameView = (TextView) findViewById(R.id.artist_name);
		artistNameView.setText(artistDataSet.getName());

		TextView artistSummaryView = (TextView) findViewById(R.id.artist_summary);
		String artist_summary = Html.fromHtml(artistDataSet.getBio_summary())
				.toString();

		if (artist_summary.length() == 0)
			artist_summary = "No artist summary available";

		String artist_bio_content = artistDataSet.getBio_content();
		String show_more = "";
		if ((artist_bio_content != null) && (artist_bio_content.length() > 0))
			show_more = "Full Biography Available...";

		artistSummaryView.setText("Summary: \n" + artist_summary + "\n"
				+ show_more);

		TextView artistTagsView = (TextView) findViewById(R.id.artist_tags);
		List<String> listTags = artistDataSet.getTags();
		String tags = "";
		if ((listTags != null) && (listTags.size() > 0)) {
			tags = "Tags: " + listTags.get(0);
			for (int i = 1; i < listTags.size(); i++)
				tags += ", " + listTags.get(i);
		}
		if (tags.length() == 0)
			tags = "No tags available";

		artistTagsView.setText(tags);

		imageView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String imgUrl = artistDataSet.getImage_mega();
				if (imgUrl == "") {
					imgUrl = artistDataSet.getImage_extraLarge();
					if (imgUrl == "") {
						imgUrl = artistDataSet.getImage_large();
						if (imgUrl == "") {
							imgUrl = artistDataSet.getImage_medium();
							if (imgUrl == "") {
								imgUrl = artistDataSet.getImage_small();
								if (imgUrl == "")
									return;
							}
						}
					}
				}
				Bundle intent_data = new Bundle();
				intent_data.putString("url", imgUrl);

				Intent intent = new Intent(getApplicationContext(),
						ImageActivity.class);
				intent.putExtras(intent_data);
				startActivity(intent);
			}
		});

		artistSummaryView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String text = artistDataSet.getBio_content();

				if ((text == null) || (text.length() <= 0))
					return;

				if (!artistDataSet.isContentParsed()) {
					String[] textArr = text.split("\n");
					text = "";
					for (int i = 0; i < textArr.length; i++)
						text += "	" + Html.fromHtml(textArr[i]).toString()
								+ "\n";
					artistDataSet.setBio_content(text);
					artistDataSet.setContentParsed(true);
				}

				Bundle intent_data = new Bundle();
				intent_data.putString("text", text);

				Intent intent = new Intent(getApplicationContext(),
						TextActivity.class);
				intent.putExtras(intent_data);
				startActivity(intent);
			}
		});
	}

	private String getArtistImage()
	{
		String default_image = artistDataSet.getImage_large();
		
		if (default_image == null)
		{
			String tmp = null;
			do
			{
				 tmp = artistDataSet.getImage_medium();
				 if (tmp != null)
					 break;
				 
				 tmp = artistDataSet.getImage_extraLarge();
				 if (tmp != null)
					 break;
				 
				 tmp = artistDataSet.getImage_small();
				 if (tmp != null)
					 break;
				 
				 tmp = artistDataSet.getImage_mega();
				 if (tmp != null)
					 break;
				
			} while (false);
			
			default_image = tmp;
		}
		
		if ((default_image == null) || (default_image.length() <= 0))
			default_image = "http://cdn.last.fm/flatness/catalogue/noimage/1/default_artist_large.png";
		return default_image;
	}

	private Bitmap urlToImage(String imageUrl) {

		LastfmURL myFileUrl = null;
		try {
			myFileUrl = new LastfmURL(imageUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		InputStream is = null;
		try {
			is = myFileUrl.openStream();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LastfmBluetoothUnavailableException e) {
			e.printStackTrace();
		}

		myFileUrl.finished();

		return BitmapFactory.decodeStream(is);
	}
}